package com.dabao.controller.admin;

import com.dabao.bean.Menu;
import com.dabao.bean.Role;
import com.dabao.controller.BaseController;
import com.dabao.query.Page;
import com.dabao.query.RoleQuery;
import com.dabao.service.MenuService;
import com.dabao.service.RoleService;
import com.dabao.util.web.MsgEnum;
import com.dabao.util.web.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kakalee on 16/4/23.
 */
@Controller
@RequestMapping("/admin/role/")
public class RoleController extends BaseController{

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @RequestMapping("")
    public String index() {
        return "admin/role/list";
    }

    @RequestMapping("/list")
    @ResponseBody
    public String list(@RequestParam(value = "draw", required = false, defaultValue = "1")String draw,
                       @RequestParam(value = "start", required = false, defaultValue = "0") int pageNo,
                       @RequestParam(value = "length", required = false, defaultValue = "0") int pageSize) {

        RoleQuery query = new RoleQuery();
        query.setOrderColumn("id");
        query.setIsDesc(1);
        query.setPage(Page.getPage(pageNo, pageSize));

        int total = roleService.selectCount(query);
        List<Role> roles = roleService.selectList(query);
        return ResponseUtils.listData(total, roles, draw);
    }

    @RequestMapping(value = "/save", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String save(@RequestParam(value = "id", required = false)Integer id,
                       @RequestParam("name")String name) {
        Role role = new Role();
        role.setId(id);
        role.setName(name);

        int result;
        if(id ==  null) {
            result = roleService.insert(role);
        }

        else {
            result = roleService.update(role);
        }

        if(result > 0) {
            return ResponseUtils.success(MsgEnum.MSG_SUCCESS.getValue());
        }
        logger.info("save role");
        return ResponseUtils.error(MsgEnum.MSG_FAIL.getValue());
    }

    @RequestMapping(value = "/delete", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String delete(@RequestParam("id")Integer id) {
        roleService.delete(id);
        return ResponseUtils.success(MsgEnum.MSG_SUCCESS.getValue());
    }

    /**
     * 编辑角色的具体权限界面
     * 先获取所有菜单
     * 再获取角色的菜单
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/detail")
    public String detail(@RequestParam("id") Integer id, Model model) {
        Role role = roleService.selectById(id);
        List<Menu> menus = menuService.selectList(null);
        List<Menu> roleMenus = roleService.selectMenus(id);

        for(Menu r : roleMenus) {
            for(Menu m : menus) {
                if(m.getId().equals(r.getId())) {
                    m.setChecked(true);
                    break;
                }
            }
        }

        roleMenus = menuTree(menus);
        model.addAttribute("roleMenus", roleMenus);
        model.addAttribute("role", role);
        return "admin/role/detail";
    }

    @RequestMapping(value = "/detailSave", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String detailSave(@RequestParam("id")Integer id, @RequestParam(value = "menuIds[]", required = false)Integer[] menuIds) {
        int result = 0;
        try {
            result = roleService.addMenus(id, menuIds);
        } catch (Exception e) {
            logger.error("addMenus error", e);
        }

        if(result > 0) {
            return ResponseUtils.success(MsgEnum.MSG_SUCCESS.getValue());
        }
        logger.info("detailSave role");
        return ResponseUtils.error(MsgEnum.MSG_FAIL.getValue());
    }

    /**
     * 将菜单变化为二级菜单的形式
     * @param menus
     * @return
     */
    private List<Menu> menuTree(List<Menu> menus) {
        List<Menu> firstLevels =  new ArrayList<Menu>();

        for(Menu menu : menus) {
            if(menu.getType() == 0) {
                menu.setChildren(new ArrayList<Menu>());
                firstLevels.add(menu);
            }
        }

        for(Menu menu : menus)
            for (Menu firstLevel : firstLevels) {
                if(firstLevel.getId() == menu.getParentId()) {
                    firstLevel.getChildren().add(menu);
                }
            }
        return firstLevels;
    }
}
